package com.yl.immodule.fragment

import android.content.Context
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.android.yl.ylicpsdk.ICPRtcEventHandler
import com.android.yl.ylicpsdk.ICPRtcManager
import com.unionbroad.app.eventbus.ChannelChangedEvent
import com.yl.immodule.R
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import javax.inject.Inject

@HiltViewModel
class IMViewModel @Inject constructor(
    private val context: Context?
): ViewModel() {
    val TAG = IMViewModel::class.java.simpleName

    private var job: Job? = null
    private var mTalkTimeSecond: Long = 0
    private val _animLiveData = MutableLiveData<Boolean>()
    val animLiveData: LiveData<Boolean> = _animLiveData
    private val _animDataLiveData = MutableLiveData<Float>()
    val animDataLiveData: LiveData<Float> = _animDataLiveData

    val status: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }
    val timer: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }
    val timer_gone: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>()
    }
    val status_gone: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>()
    }
    val voice_gone: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>()
    }
    val statusDrawable: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>()
    }
    val remote_talking: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }
    val remote_talking_gone: MutableLiveData<Int> by lazy {
        MutableLiveData<Int>()
    }
    private var mEventHandler: ICPRtcEventHandler? = null
    private val sDurationTimerFormat = SimpleDateFormat("mm:ss:SSS")
    init {
        mEventHandler = aICPRtcEventHandler()
        ICPRtcManager.getsInstance().addEventHandler(mEventHandler)

    }
    override fun onCleared() {
        super.onCleared()
        ICPRtcManager.getsInstance().removeEventHandler(mEventHandler)
    }
    fun startTalkTimer() {
        job = viewModelScope.launch {
            while (isActive) {
                mTalkTimeSecond++
                timer_gone.postValue(View.VISIBLE)
                var time = sDurationTimerFormat.format(mTalkTimeSecond * 100)
                if (time.length >= 2) {
                    // 00:00:000，去掉最后毫秒里的两个0
                    time = time.substring(0, time.length - 2)
                }
                timer.postValue(time)
                // 执行循环操作
                delay(100) // 例如，每隔一秒执行一次
            }
        }
        _animLiveData.postValue(true)
//        voice_gone.value = View.VISIBLE
//        voice.setImageResource(R.drawable.ic_voice0)
        mTalkTimeSecond = 0
    }
    private fun stopTalkTimer() {
        timer_gone.postValue(View.GONE)
        mTalkTimeSecond = 0
        _animLiveData.postValue(false)
        _animDataLiveData.postValue(0f)
        job?.cancel()
    }

    inner class aICPRtcEventHandler: ICPRtcEventHandler() {
        override fun onPttStateEvent(sessionId: Long, channelId: String?, state: Int) {
            Log.d(TAG, "onPttStateEvent")
            if (TextUtils.isEmpty(channelId)) {
                status.postValue("当前无附着频道")
            } else {
                //当前已经连接
                if (state == PttState.CONNECTED) {
                    onPttIdle()
                } else if (state == PttState.CONNECTING) {
                    status.postValue("正在连接")
                } else {
                    status.postValue("未连接")
                }
            }
            val channel = ICPRtcManager.getsInstance().currentPttChannel
        }

        /**
         * 当前对讲组空闲
         */
        override fun onPttIdle() {
            Log.d(TAG, "onPttIdle")
            status.postValue("空闲")
            statusDrawable.postValue(R.drawable.media_idle)
            remote_talking_gone.postValue(View.GONE)
            stopTalkTimer()
        }

        /**
         * 正在申请话语权
         */
        override fun onPttRequesting() {
            Log.d(TAG, "onPttRequesting")
            remote_talking_gone.postValue(View.GONE)
//            voice.setVisibility(View.GONE)
            status_gone.postValue(View.VISIBLE)
            status.postValue("申请中")
            statusDrawable.postValue(R.drawable.media_listen)
        }

        /**
         * 话语权被抢
         */
        override fun onPttKicked() {
            Log.d(TAG, "onPttKicked")
        }

        /**
         * 对讲组成员有人加入或退出
         *
         * @param total 总人数
         * @param join  True:有人加入  False:有人退出
         * @param which 为空时：表示：加入或退出成员id, 如果是-1标示刚进入频道的通知，并且此时频道是idle状态
         */
        override fun onPttMemberJoinOrLeave(total: Int, join: Boolean, which: String) {
            //如果是-1标示刚进入频道的通知，并且此时频道是idle状态，一般来说，只需要处理非"-1"的情况
        }

        override fun onPttMemberChanged(members: ArrayList<String>) {
        }

        /**
         * 有人在讲话
         *
         * @param isRemote True:远端有人讲话  False:本机正在讲话
         * @param uid      正在讲话者Id
         * @param total    当前对讲组总人数
         * @param fromChannelNumber 当前组
         */
        override fun onPttTalking(
            isRemote: Boolean,
            uid: String,
            total: Int,
            fromChannelNumber: Long
        ) {
            Log.d(TAG, "onPttTalking")
            if (isRemote) {
                stopTalkTimer()
                val user = ICPRtcManager.getsInstance().getUser(uid)
                val name = if (user != null) user.name else uid
                val tips = "$name 正在讲话"
                remote_talking.postValue(tips)
                remote_talking_gone.postValue(View.VISIBLE)
                status.postValue("")
                statusDrawable.postValue(R.drawable.media_listen)
                _animLiveData.postValue(true)
            } else {
                startTalkTimer()
                remote_talking_gone.postValue(View.GONE)
                status.postValue("")
                statusDrawable.postValue( R.drawable.media_talk)
            }
        }

        override fun onPttVoiceDecibelChanged(decibel: Int, isRemote: Boolean) {
            _animDataLiveData.postValue(decibel.toFloat())
        }

        /**
         * 对讲组解散
         * @param channelId 对讲组id
         */
        override fun onPttDisband(channelId: String) {
            Toast.makeText(context, "对讲组解散", Toast.LENGTH_SHORT).show()
        }

        override fun onChannelChangedEvent(event: ChannelChangedEvent) {
            //发生对讲组切换，此时刷新对讲UI
            if (event.action === ChannelChangedEvent.ACTION_SWITCH) {
                //调用该接口，会重新得到 public void onPttStateEvent(String channelId, int state) 回调
                ICPRtcManager.getsInstance().pttStateNotify()
            } else if ((event.action === ChannelChangedEvent.ACTION_ADD_USER) || (event.action === ChannelChangedEvent.ACTION_DEL_USER) || (event.action === ChannelChangedEvent.ACTION_EDIT_USER)) {
                //TODO
            } else if (event.action === ChannelChangedEvent.ACTION_ADD_GROUP || event.action === ChannelChangedEvent.ACTION_DEL_GROUP) {
                //TODO
            }
        }
    }
}